package com.example.djetpack.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel

class SavedStateViewModel(val savedState: SavedStateHandle) : ViewModel() {

    private val KEY_HOME_PAGE_DATA="key_home_page_data"
    private val initData = MutableLiveData<List<String>>()
    fun loadInitData(): LiveData<List<String>> {
        if(initData.value==null){
            //1.from memory .
            //加载数据的时候，先从savedState中尝试读取,如果有直接内存复用
            val memoryData =savedState.get<List<String>>(KEY_HOME_PAGE_DATA)
            if(memoryData!=null){
                initData.postValue(memoryData)
            }else{
                //2.from remote
                val remoteData = fetchDataFromRemote()
                //然后存储在savedState以备不时之需,数据模型需要使用parceable接口
                //这种写法,即便页面因配置变更，内存不足被回收
                //页面重建后，我们都能第一时间复用之前的数据，从而快速渲染页面
                //这种能力，对于一级页面尤其首页是至为重要的
                savedState.set(KEY_HOME_PAGE_DATA,remoteData)
                initData.postValue(remoteData)
            }
        }
        return initData
    }

    private fun fetchDataFromRemote(): List<String> {

        return mutableListOf()
    }
}